import $ from "./jq.extend";
import base64 from "./base64";
import config from "../Config";
import gx from "../gx";

let url = config.ApiUrl;

export default {
    //请求Token
    CallAuthentication(loginObj, options) {
		// const {loginCode,loginName, password}={...loginObj};
        let opts = {
            url: url + "/token",
            method: "post",
            header: {
                ContentType: 'Application/x-www-form-urlencoded',
                clientID: "Basic " + base64.btoa(config.ClientID + ":")
            },
            data: loginObj,
            timeout: 15000,
        };

        $.extend(opts, options);

        uni.request(opts);
    },


    //刷新Token
    CallRefreshToken(options) {
        let _token = uni.getStorageSync(config.TokenKey);

        let opts = {
            url: url + "/token",
            method: "post",
            header: {
                'Content-Type': 'Application/x-www-form-urlencoded',
                'Authorization': "Basic " + base64.btoa(config.ClientID + ":")
            },
            data: "refresh_token=" + _token.refresh_token + "&grant_type=refresh_token",
            timeout: 15000,
        };

        $.extend(opts, options);

        uni.request(opts);
    },


    //请求Api
    Call(options) {
        let _token = uni.getStorageSync(config.TokenKey);

        let opts = {
            timeout: 15000,
        };

        $.extend(opts, options);

        if (opts.hasToken && !gx.IsEmpty(_token)) {
            $.extend(opts.header, { "Authorization": "Bearer " + _token.access_token })
        }

        //如果传输的数据是object类型，则转换成json字符串
        if (opts.data && typeof opts.data === "object" && !opts.isUpload) {
            opts.data = gx.SerializeObject(opts.data);
        }

        uni.request(opts);
    }
}